import {formatCheckpointFlow} from "src/utils/format-flow";
import {nanoid} from "nanoid";

export const version = '2023.11.10.1'

export function formatConfig(config) {
  // console.log('format config', config)
  const checkpoint_list = []

  // 转换排序字段为数字（可能有数据是字符串）
  config.flow_list.forEach(function (checkpoint) {
    checkpoint.sort = parseInt(checkpoint.sort)
  })

  // 重新排序
  config.flow_list.sort((a, b) => a.sort - b.sort)

  // 处理需要导出的checkpint_list
  config.flow_list.forEach(function (checkpoint) {
    if (checkpoint.code === 'WELCOME') {
      // 对欢迎页面做一些预处理
      checkpoint.display = false
      checkpoint.sort = 0
      checkpoint.gps = ''
      checkpoint.status = 0
    }

    // 更新工作流
    checkpoint.workflow = {}
    formatCheckpointFlow(checkpoint)

    // 小程序使用数据，精简任务的UI信息
    checkpoint_list.push({
      id: checkpoint.id,
      code: checkpoint.code,
      name: checkpoint.name,
      memo: checkpoint.memo,
      group: checkpoint.group,
      sort: checkpoint.sort,
      pic: checkpoint.pic,
      pic2: checkpoint.pic2,
      gps: checkpoint.gps,
      display: checkpoint.display,
      status: checkpoint.status,
      workflow: checkpoint.workflow,
    })
  })

  // 保存格式化后的数据
  config.checkpoint_list = checkpoint_list
  // saveGameConfig(config)

  return config
}

export function saveGameConfig(config) {
  console.log('save config', config)
  localStorage.setItem('game_config', JSON.stringify(config))
}

export function getGameConfig() {
  const config = JSON.parse(localStorage.getItem('game_config'))
  console.log('get config', config)
  return config
}

export function saveCheckpointList(checkpoint_list) {
  console.log('save list', checkpoint_list)
  // localStorage.setItem('checkpoint_list', JSON.stringify(checkpoint_list))
  const config = getGameConfig()
  config.flow_list = checkpoint_list
  saveGameConfig(config)
}

export function getCheckpointList() {
  const config = getGameConfig()
  // console.log('checkpoint list', config.flow_list)
  return config.flow_list
}

export function getCheckpointByID(list, id) {
  for (let index = 0; index < list.length; index++) {
    if (list[index].id === id) {
      return list[index]
    }
  }
}

export const defult_checkpoint_list = [
  {
    "id": nanoid(),
    "group": "WELCOME",
    "code": "WELCOME",
    "display": false,
    "gps": "",
    "memo": "",
    "name": "安全须知",
    "sort": 0,
    "status": 0,
    // "workflow": {},
    // "flow": {},
  },
]

export const default_page_config = {
  "waiting": {},
  "login": {},
  "index": {},
  "task": {},
  "process": {},
  "rank": {},
  "plugin": {},
}
